package com.aliang.shopping.util.ali;

import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.config.PayConfig;
import com.aliang.shopping.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 阿里支付工具类
 */
@Component
public class PayTemplate {

    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";


    @Resource
    private PayConfig payConfig;


    /**
     * 获取支付表单
     *
     * @param orderId
     * @return
     * @throws Exception
     */
    public String pay(String orderId, BigDecimal price, String name) {

        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.getGatewayUrl(), payConfig.getAppId(),
                payConfig.getAppPrivateKey(), FORMAT, CHARSET, payConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setNotifyUrl(payConfig.getNotifyBaseUrl() + payConfig.getNotifyUrl()); //异步回调地址

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderId);  // 我们生成的订单编号
        bizContent.put("total_amount", price); // 订单的总金额，
        bizContent.put("subject", name);   // 支付的名称
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        bizContent.put("qr_pay_mode", "2");  // 表单格式
        bizContent.put("qrcode_width", "200");  // 二维码宽度
        request.setBizContent(bizContent.toString());
        request.setReturnUrl(payConfig.getReturnUrl()); // 支付完成后自动跳转到本地页面的路径
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            throw new ServiceException(ResultCodeEnum.PAY_ERROR);
        }
        return form;
    }

    /**
     * 发起退款
     */
    public String outPay(String payNo, String orderId, BigDecimal price, String name) throws AlipayApiException {

        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.getGatewayUrl(), payConfig.getAppId(),
                payConfig.getAppPrivateKey(), FORMAT, CHARSET, payConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();

        // 设置商户订单号
        model.setOutTradeNo(payNo);


        // 设置退款金额
        model.setRefundAmount(price.toString());

        // 设置退款原因说明
        model.setRefundReason("正常退款");

        // 设置退款请求号
        model.setOutRequestNo(orderId);

        // 设置查询选项
        List<String> queryOptions = new ArrayList<>();
        queryOptions.add("refund_detail_item_list");
        model.setQueryOptions(queryOptions);

        request.setBizModel(model);

        AlipayTradeRefundResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
            return response.getBody();
        } else {
            System.out.println("调用失败");
        }
      return response.getBody();
    }
}
